<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * @filename mconfigs.php
 * 配置模型
 * @author hmw
 *
 */

class Mconfigs extends Model {

    function Mconfigs() {
        parent::Model();
    }

    /**
     * 根据配置项获取配置内容
     * @param $key
     * @return mixed
     */
    function get_config_value($key){
    	$query = $this->db->get_where('configs',array('cfg_key'=>$key));
    	$row = $query->row();
    	return $row ? $row->cfg_value : FALSE;
    }

    function get_index_configs(){
    	$this->db->like('cfg_key','index_','after');
    	$query = $this->db->get('configs');
    	$res = $query->result_array();
    	$configs = array();
    	if ($res){
    		foreach($res as $arr){
    			$configs[$arr['cfg_key']] = $arr['cfg_value'];
    		}
    	}
    	return $configs;
    }

    function get_site_config(){
    	$this->db->like('cfg_key','site_','after');
    	$query = $this->db->get('configs');
    	$res = $query->result_array();
    	$configs = array();
    	if ($res){
    		foreach($res as $arr){
    			$configs[$arr['cfg_key']] = $arr['cfg_value'];
    		}
    	}
    	return $configs;
    }

    function update_configs($configs){
    	if (is_array($configs) && count($configs)){
    		$succ = 0;
    		$fail = 0;
    		foreach($configs as $key=>$value){
    			if(self::update_config($key,$value)){
    				$succ++;
    			} else {
    				$fail++;
    			}
    		}
    		if($succ == count($configs)){
    			return TRUE;
    		} else {
    			return FALSE;
    		}
    	} else {
    		return FALSE;
    	}
    }

    function update_config($key,$value){
    	$this->db->where(array('cfg_key'=>$key));
    	return $this->db->update('configs',array('cfg_value'=>$value));
    }


    function get_banus_config($utype=''){
    	if($utype == ''){
    		$this->db->like('cfg_key','banus_discount_','after');
	    	$query = $this->db->get('configs');
	    	$res = $query->result_array();
	    	$configs = array();
	    	if ($res){
	    		foreach($res as $arr){
	    			$configs[$arr['cfg_key']] = $arr['cfg_value'];
	    		}
	    	}
	    	return $configs;
    	}
    	$key = 'banus_discount_'.strtolower($utype);
    	return self::get_config_value($key);
    }

    function get_config(){
        $query = $this->db->get('configs');
        $res = $query->result_array();
        $configs = array();
        if ($res){
            foreach($res as $arr){
                $configs[$arr['cfg_key']] = $arr['cfg_value'];
            }
        }
        return $configs;
    }

}

?>